from django.shortcuts import render
from .models import *
from django.core.paginator import Paginator
from django.utils import timezone
import random

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import time
import datetime



# @csrf_exempt
def comment(request):
    '''评论功能'''
    commentID = request.POST.get('commentID')
    commentName = request.POST.get('commentName')
    commentEmail = request.POST.get('commentEmail')
    content = request.POST.get('content')
    print('----------1234-------------')

    try:
        # 保存评论内容
        comment = Comment()
        # 这里对象写错了，导致出现500服务错误
        comment.content = content
        comment.time = time.time()
        comment.name = commentName
        comment.email = commentEmail
        comment.post_id = commentID
        comment.save()
    except Exception as e:
        pass
    finally:
        # 1. 获取当前文章的所有评论
        detail_comment = Comment.objects.filter(post=commentID).order_by('-time')[:100]
        # 2.序列化
        data_list = []
        for com in detail_comment:
            dic = {}
            dic['name'] = com.name
            dic['time'] = com.time.strftime("%Y-%m-%d")
            dic['content'] = com.content
            data_list.append(dic)
        return JsonResponse({"data": data_list})


@csrf_exempt
def zan(request):
    '''点赞功能'''
    try:
        # 获取点赞文章id
        id_ = request.POST.get("id")
        # 获取对应文章对象
        # 注意这里get方法不要写错了
        p = Post.objects.get(pk=id_)
    except Exception as e:
        print("参数错误了")
        return JsonResponse({'code': 1, 'msg': '参数错误'})
    else:
        # 设置点赞时间限制，几秒钟能点击一次，几分钟能点击一次，几小时能点击一次，一天能点击一次等等
        id_zan = request.session.get(f"{id_}zan")
        # 没有获取session则表示用户没有对当前文章点过赞 not id_zan
        # 过了时间戳就允许再次点赞 time.time() > id_zan
        # if not id_zan or time.time() > id_zan
        if not id_zan or time.time() > id_zan:
            p.zan += 1
            p.save()
            time_now = datetime.datetime.now()
            time_now_zero = datetime.datetime.strptime(time_now.strftime('%Y-%m-%d'), '%Y-%m-%d')
            time_m = time_now_zero + datetime.timedelta(days=1)
            request.session[f"{id_}zan"] = time_m.timestamp()
            return JsonResponse({'code': 200, 'msg': '点赞成功', 'data': p.zan})
        else:
            return JsonResponse({'code': -1, 'msg': '今日已赞，请明日再来'})


# Create your views here.
def index(request):
    # 1.设置每日一句
    sen_all = Sentence.objects.all()
    random_sen = random.choice(sen_all)
    # 4.设置分类
    classify = request.GET.get("classify")
    if not classify or classify is None:
        # 2.设置最新文章(首先)
        last_post_list = Post.objects.all()
    elif classify == '1':
        last_post_list = Post.objects.filter(classify="网站前端")
    else:
        last_post_list = Post.objects.filter(classify="后端技术")

    # 3.最新文章--实现分页功能(其次)--每页两篇文章
    per_post_obj = Paginator(last_post_list, 2)
    # 获取第一页的两篇文章
    page = request.GET.get("page")
    if not page:
        page = 1
    last_post_list = per_post_obj.page(page)
    # 5.本周热搜
    '''
        获取当前时间，我们要推算出本周周一的日期，之后使用过滤，只保留这周的文章
    '''
    # 获取当前时间对象
    now_time = timezone.now()
    # 对时间进行格式化
    now_time_zero = datetime.datetime.strptime(now_time.strftime("%Y-%m-%d"), '%Y-%m-%d')
    # 获取当前是周几
    week_day = now_time_zero.isoweekday()
    # 获取周一的时间
    m_time = now_time_zero - timezone.timedelta(days=(week_day - 1))
    # 获取周一到当前时间的所有时间
    print(m_time, now_time)
    hot_post = Post.objects.filter(modify_time__range=(m_time, now_time)).order_by('-look')[:5]

    # 6.设置轮播图
    adv = Post.objects.filter(adv=True)

    # 7.右侧热门推荐
    right_hot_post = Post.objects.order_by('-look')[:5]

    # 最新评论
    latest_comment = Comment.objects.all().order_by('-time')[:5]
    print("最新评论：", latest_comment)

    context = {
        "random_sen": random_sen,
        "last_post_list": last_post_list,
        "classify": classify,
        "hot_post": hot_post,
        "adv": adv,
        "right_hot_post": right_hot_post,
        "latest_comment": latest_comment
    }
    return render(request, 'myblog/index.html', context=context)


def detail(request):
    # 1.设置每日一句
    sen_all = Sentence.objects.all()
    random_sen = random.choice(sen_all)
    # 7.右侧热门推荐
    right_hot_post = Post.objects.order_by('-look')[:5]
    print('----------------')
    # 设置跳转到文章详情页--这里需要考虑，当没有文章是应该什么处理
    post_id = request.GET.get("id")
    # post_detail = get_object_or_404(Post, pk=id)  # 不要使用这个不然会出现错误
    post_detail = Post.objects.filter(pk=post_id).first()

    # 获取上一篇
    prev_post = Post.objects.filter(id__lt=post_id).order_by('-id')[:1]
    # 获取下一篇
    next_post = Post.objects.filter(id__gt=post_id).order_by('id')[:1]

    # 相关推荐：tags标签去做相关推荐
    tags = post_detail.tags.all()  # 获取所有tags标签
    tag_post_list_all = []
    for tag in tags:
        tag_post_list = tag.post_set.all()  # 反向查询，通过一个标签对象，拿到关联的所有文章 模型类小写_set.all()
        tag_post_list_all.extend(tag_post_list)
    # 排除相关推荐上面的文章
    tag_post_list_all = [p for p in tag_post_list_all if p.id != post_detail.id]
    # 去除重复
    tag_post_list_all = list(set(tag_post_list_all))

    # 需要考虑得到的标签的最终文章数量情况
    if (len(tag_post_list_all)) >= 8:
        # 随机获取8篇文章
        random_post_list = random.sample(tag_post_list_all, 8)
    elif (len(tag_post_list_all)) == 0:
        # 当没有的时候
        random_post_list = []
    else:
        # 当有不足8篇的时候
        random_post_list = []
        for i in range(8):
            random_post_list.append(random.choice(tag_post_list_all))

    # 右侧最新评论
    latest_comment = Comment.objects.all().order_by('-time')[:5]

    context = {
        "random_sen": random_sen,
        "right_hot_post": right_hot_post,
        "post_detail": post_detail,
        "prev_post": prev_post,
        "next_post": next_post,
        "random_post_list": random_post_list,
        "latest_comment": latest_comment
    }
    return render(request, 'myblog/content.html', context=context)
